package red.mlz.module.module.excel.service;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.service.CategoryService;
import red.mlz.module.module.excel.entity.DownloadData;
import red.mlz.module.module.excel.entity.UploadData;
import red.mlz.module.utils.BaseUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExcelService {

    @Autowired
    private CategoryService categoryService;

    public List<UploadData> read(MultipartFile file) {
        List<UploadData> uploadDataList = new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDataList)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return uploadDataList;
    }

    public void download(HttpServletResponse response) {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<Category> categoryList = categoryService.categoryList();
            List<DownloadData> downloadDataList = new ArrayList<>();
            if (!BaseUtils.isEmpty(categoryList)) {
                downloadDataList = categoryList.stream()
                        .map(category -> {
                            return DownloadData.builder()
                                    .id(category.getId())
                                    .name(category.getName())
                                    .imageUrl(category.getImageUrl())
                                    .parentId(category.getParentId())
                                    .createTime(category.getCreateTime() != null ?
                                            BaseUtils.timeStamp2Date(category.getCreateTime()) : "")
                                    .updateTime(category.getUpdateTime() != null ?
                                            BaseUtils.timeStamp2Date(category.getUpdateTime()) : "")
                                    .isDeleted(category.getIsDeleted())
                                    .build();
                        }).collect(Collectors.toList());
            }

            EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("分类数据").doWrite(downloadDataList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
